package com.example.accelerometerrecorder;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener{

	private SensorManager mSensorManager;
	private Sensor mAccelerometer;

	//Storage variables
	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	FileWriter writer;

	//WakeLock to prevent phone from sleeping
	WakeLock wakelock;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

		PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
		wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "AccelRecorder");

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];

		//get accelerometer values

		writeLine(System.currentTimeMillis()+","+x+","+y+","+z+"\n");
	}
	
	public void btnMark_onClick(View view){
		writeLine(System.currentTimeMillis()+",Mark,\n");
	}

	public void setupWriter(){
		File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
		
		System.out.println("File directory: "+dir.toString());
		
		Calendar cal = Calendar.getInstance();
		
		File record = new File(dir, 
				"AccelRecord_"
				+cal.get(Calendar.MONTH)+"-"
				+cal.get(Calendar.DAY_OF_MONTH)+"-"
				+cal.get(Calendar.YEAR)+"-"
				+cal.get(Calendar.HOUR_OF_DAY)+"-"
				+cal.get(Calendar.MINUTE)+"-"
				+cal.get(Calendar.SECOND)
				+".csv");
		System.out.println("Filename: "+record.toString());

		System.out.println("File exists: "+record.exists());
		System.out.println("File can write: "+record.canWrite());
		try {
			
			record.createNewFile();
		} catch (IOException e) {
			System.out.println("setup writer could not create file");
			e.printStackTrace();
		}

		try {
			writer = new FileWriter(record);
		} catch (IOException e) {
			System.out.println("setup writer could not create FileWriter");
			e.printStackTrace();
		}

	}

	public void checkStorageState(){
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
			System.out.println("External Storage Readable + Writable");
		} 
		else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
			System.out.println("External Storage Readable Only");
		} 
		else {
			// Something else is wrong. It may be one of many other states, but all we need
			//  to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
			System.out.println("External Storage Not Readable or Writable");
		}
	}

	public void writeLine(String line){
		if (writer!=null){
			try {
				writer.append(line);
				writer.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void btnRecord_onClick(View view){
		wakelock.acquire();

		checkStorageState();
		
		setupWriter();
		
		//register for accelerometer updates
		mSensorManager.registerListener(
				this, 
				mAccelerometer, 
				SensorManager.SENSOR_DELAY_NORMAL);
		
		
		toast("Recording!");
	}

	public void btnStop_onClick(View view){

		//unregister for accelerometer updates
		mSensorManager.unregisterListener(this);

		//complete all writing to file
		if(writer!=null){
			try {
				writer.flush();
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		//release the wakelock to allow screen to turn off.
		wakelock.release();
		toast("Stopped Recording!");
	}
	
	private void toast(String messageText) {
		Toast toast = Toast.makeText(
				this,
				messageText,
				Toast.LENGTH_SHORT
		);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

}
